layui.use(['layer','form','table'], function() {
    var layer = layui.layer, form = layui.form, table = layui.table,
    fn = {
        statusId:'',//清单查询状态
        clickQuery:'1',//是否点击了查询
        batchDeclareSize:0,//批量申报记录数
        init:function (){
            var id = getUrlParam('id');
            if(isNotEmpty(id)){
                show_loading();
                $.get('/declare/vehicleDeclare/detail',{id:id},function (res) {
                    if(isSuccessWarnClose(res)){
                        var vehicleDeclare = res.data;
                        fn.statusId = vehicleDeclare.statusId;
                        form.val('headForm',vehicleDeclare);
                        feeMarkSelect();
                        insurMarkSelect();
                        $('#totalNum').html(vehicleDeclare.totalNum);
                        $('#totalPrice').html(vehicleDeclare.totalPrice);
                        $('#totalGrossWeight').html(vehicleDeclare.totalGrossWeight);
                        $('#totalNetWeight').html(vehicleDeclare.totalNetWeight);

                        fn.vehicleDetailedList({'vehicleDeclareId':id});

                    }
                });
            }
        },
        // 清单列表
        vehicleDetailedList:function (params){
            table.render({
                elem:'#vehicle-detailed-list',id:'vehicle-detailed-list',page:true,method:'post',height:'312',
                url:'/declare/vehicleDeclareOrder/pageList',where:params,response:{msgName:'message',statusCode: '1'}
                ,cols: [[
                    {checkbox: true,width:40, fixed: true}
                    ,{field:'rowNo',width:40,title: '项号',align:'center', fixed: true}
                    ,{field:'statusName', width:90, title: '状态',align:'center',templet:'#statusTemp', fixed: true,event:'showInvtMemo'}
                    ,{field:'detailedNo', width:144, title: '清单编号',event:'showGood'}
                    ,{field:'waybillNo', width:150, title: '运单编号',event:'showGood'}
                    ,{field:'orderNo', width:144, title: '订单编号',event:'showGood'}
                    ,{field:'bookNo', width:80, title: '账册编号',event:'editHead'}
                    ,{field:'declTotal', width:80, title: '商品金额',align:'right',event:'editHead'}
                    ,{field:'amountPrice', width:80, title: '收款金额',align:'right',event:'editHead'}
                    ,{field:'tradeCurrName', width:70, title: '币制',align:'center',event:'editHead'}
                    ,{field:'grossWeight', width:80, title: '毛重(KG)',align:'right',event:'editHead'}
                    ,{field:'netWeight', width:80, title: '净重(KG)',align:'right',event:'editHead'}
                    ,{field:'number', width:60, title: '件数',align:'center',event:'editHead'}
                    // ,{field:'feeStr', width:120, title: '运费',align:'center'}
                    // ,{field:'insurStr', width:120, title: '保费',align:'center'}
                    // ,{field:'wrapTypeName', width:80, title: '包装种类',align:'center'}
                    ,{field:'gname', width:160, title: '商品名称',event:'editHead'}
                    //,{field:'codeTs', width:100, title: '商品编码',align:'center'}
                    ,{field:'orderStatusName', width:100, title: '订单状态',align:'center',templet:'#orderStatusTemp'}
                    ,{field:'receiptStatusName', width:100, title: '收款单状态',align:'center',templet:'#receiptStatusTemp'}
                    ,{field:'logisticsStatusName', width:100, title: '运单状态',align:'center',templet:'#logisticsStatusTemp'}
                    ,{field:'inventoryCancelStatusName', width:100, title: '撤销清单状态',align:'center',templet:'#inventoryCancelStatusTemp',event:'showInvtCancelGood'}
                ]],
                done: function(res, curr, count){
                    fn.batchDeclareSize = count;
                }
            });
        },
        //清单表体
        vehicleGoodsList:function (params){
            table.render({
                elem:'#vehicle-goods-list',id:'vehicle-goods-list',page:false,method:'post',height:'200',
                url:'/declare/vehicleDeclareGoods/list',where:params,response:{msgName:'message',statusCode: '1'}
                ,cols: [[
                    {checkbox: true,width:40, fixed: true}
                    ,{field:'rowNo',width:40,title: '序号',align:'center', fixed: true}
                    ,{field:'codeTs', width:120, title: '商品编码',align:'left'}
                    ,{field:'gname', width:144, title: '商品名称',align:'left'}
                    ,{field:'gspec', width:260, title: '规格型号',align:'left'}
                    ,{field:'qcodeTs', width:120, title: '企业商品货号',align:'left'}
                    ,{field:'qgname', width:144, title: '企业商品名称',align:'left'}
                    ,{field:'qgspec', width:100, title: '企业商品描述',align:'left'}
                    ,{field:'gunitName', width:80, title: '申报计量单位',align:'left'}
                    ,{field:'unit1Name', width:80, title: '法定计量单位',align:'left'}
                    ,{field:'unit2Name', width:80, title: '第二计量单位',align:'left'}
                    ,{field:'gqty', width:60, title: '申报数量',align:'left'}
                    ,{field:'qty1', width:120, title: '法定数量',align:'left'}
                    ,{field:'qty2', width:120, title: '法定第二数量',align:'left'}
                    ,{field:'tradeCurrName', width:80, title: '币制',align:'left'}
                    ,{field:'declPrice', width:160, title: '单价',align:'left'}
                    ,{field:'declTotal', width:100, title: '总价',align:'left'}
                    ,{field:'destinationCountryName', width:100, title: '商品目的国',align:'left'}
                    ,{field:'barCode', width:100, title: '条形码',align:'left'}
                    ,{field:'booksGoodsNo', width:100, title: '账册备案资料',align:'left'}
                    ,{field:'gmemo', width:100, title: '备注',align:'left'}
                ]]
            });
        },
        getInventoryStatus(){
            $.get(rurl('declare/vehicleDeclare/statusTotal'),{'id':getUrlParam('id')},function (res) {
                if(isSuccess(res)){
                    var $statusId = $('#statusId');
                    $statusId.append("<option value=''>清单状态</option>");
                    $.each(res.data||[],function (i,o) {
                        if(o.total != null && o.total != '') {
                            $statusId.append('<option value="'+o.statusId+'" ' + '>'+o.statusDesc+'('+o.total+')'+ '</option>');
                        } else {
                            $statusId.append('<option value="'+o.statusId+'" ' + '>'+o.statusDesc+'</option>');
                        }
                    });
                    layui.form.render('select');
                }
            });
        },
        getOrderStatus(){
            $.get(rurl('declare/vehicleDeclare/orderStatusTotal'),{'id':getUrlParam('id')},function (res) {
                if(isSuccess(res)){
                    var $orderStatus = $('#orderStatus');
                    $orderStatus.append("<option value=''>订单状态</option>");
                    $.each(res.data||[],function (i,o) {
                        if(o.total != null && o.total != '') {
                            $orderStatus.append('<option value="'+o.statusId+'" ' + '>'+o.statusDesc+'('+o.total+')'+ '</option>');
                        } else {
                            $orderStatus.append('<option value="'+o.statusId+'" ' + '>'+o.statusDesc+'</option>');
                        }
                    });
                    layui.form.render('select');
                }
            });
        },
        //导出司机纸
        exportDriverPaper(){
            var id = getUrlParam('id');
            var ids = [];
            var datas = layui.table.checkStatus("vehicle-detailed-list").data;
            $.each(datas,function (i,o) {
                ids.push(o.id);
            });
            window.open(rurl("/declare/vehicleDeclareExport/exportDriverPaper?id=" + id + "&memberIds=" + ids.join(",")),'_blank');
        },
        //导出明细单
        exportMember(){
            var id = getUrlParam('id');
            var ids = [];
            var datas = layui.table.checkStatus("vehicle-detailed-list").data;
            $.each(datas,function (i,o) {
                ids.push(o.id);
            });
            window.open(rurl("/declare/vehicleDeclareExport/exportMember?id=" + id + "&memberIds=" + ids.join(",")),'_blank');
        },
        //导出原数据
        exportOriginData(){
            show_loading();
            var id = getUrlParam('id');
            var ids = [];
            var datas = layui.table.checkStatus("vehicle-detailed-list").data;
            $.each(datas,function (i,o) {
                ids.push(o.id);
            });
            $.post(rurl("/declare/vehicleDeclareExport/exportOriginData?id=" + id + "&memberIds=" + ids.join(",")),function (res)
            {if(isSuccessWarn(res)){
                exportFile(res.data);
            }});
        },
        //导出战场资料
        exportBattle(){
            var id = getUrlParam('id');
            window.open(rurl('declare/vehicleDeclareExport/exportBattle?id=' + id));
        },
        delete(){
            var id = getUrlParam('id');
            confirm_inquiry('谨慎操作，数据删除后将无法恢复，请确认是否删除？',function () {
                $.post(rurl("/declare/vehicleDeclare/delete?id=" + id),function (res) {
                    if(isSuccess(res)) {
                        parent.reloadList();
                        closeThisWin("删除成功");
                    }
                });
            });
        },
        waybillCancel(){
            show_loading();
            var id = getUrlParam('id');
            $.post(rurl("/declare/vehicleDeclare/waybillCancelDeclare?id=" + id),function (res) {
                if(isSuccess(res)) {
                    parent.reloadList();
                    closeThisWin("提交成功，请耐心等待回执");
                }
            });
        },
        saveDec(){
            show_loading();
            postJSON("declare/vehicleDeclare/saveDec",$('#headForm').serializeJson(),function (res) {
                if(isSuccess(res)) {
                    parent.reloadList();
                    closeThisWin("保存成功");
                }
            });
        },
    };
    fn.init();
    fn.getInventoryStatus();
    fn.getOrderStatus();
    $('#exportDriverPaper').click(function (){
        fn.exportDriverPaper();
    });
    $('#exportMember').click(function (){
        fn.exportMember();
    });
    $('#exportOriginData').click(function (){
        fn.exportOriginData();
    });
    $("#exportBattle").click(function () {
       fn.exportBattle();
    });
    $("#declare").click(function () {
        openwin(rurl('online/declare/declare.html?id='+getUrlParam('id') + "&statusId=" + fn.statusId),'整车申报',{area: ['700px', '700px'],shadeClose:true});
    });
    $("#batch-declare").click(function () {
        var ids = [];
        var datas = layui.table.checkStatus("vehicle-detailed-list").data;
        $.each(datas,function (i,o) {
            ids.push(o.id);
        });
        if(ids != null && ids.length > 0) {
            fn.clickQuery = '0';//按勾选条件，即使其他查询条件传了也不查询
        } else {
            if(fn.clickQuery == '0') { //输了查询条件，但没点击查询，也没有勾选数据，不能把查询条件带过去，防止按条件查询了
                $("#s_docNo").val('');
                $("#statusId").val('');
                $("#orderStatus").val('');
                $("#s_codeTs").val('');
            }
        }
        let title = '批量申报（' + ( (ids != null && ids.length > 0) ?  ('按选中' + ids.length) : ('按筛选结果' + fn.batchDeclareSize) ) +  '条，请仔细确认操作的数据）';
        openwin(rurl('online/declare/batch_declare.html?id='+getUrlParam('id') + "&statusId=" + $("#statusId").val()  + "&orderStatus=" + $("#orderStatus").val() + "&vehicleStatusId=" + fn.statusId + "&waybillOrderNo=" + $("#s_docNo").val() + "&codeTs=" + $("#s_codeTs").val()  + "&batchDeclareSize=" + fn.batchDeclareSize + "&memberIds=" + ids.join(",") ),title,{area: ['700px', '500px'],shadeClose:true});
    });
    $("#amendNo").click(function () {
        var ids = [];
        var datas = layui.table.checkStatus("vehicle-detailed-list").data;
        $.each(datas,function (i,o) {
            ids.push(o.id);
        });
        if(ids != null && ids.length > 0) {
            fn.clickQuery = '0';//按勾选条件，即使其他查询条件传了也不查询
        } else {
            if(fn.clickQuery == '0') { //输了查询条件，但没点击查询，也没有勾选数据，不能把查询条件带过去，防止按条件查询了
                $("#s_docNo").val('');
                $("#statusId").val('');
                $("#orderStatus").val('');
                $("#s_codeTs").val('');
            }
        }
        let title = '修改单号（' + ( (ids != null && ids.length > 0) ?  ('按选中' + ids.length) : ('按筛选结果' + fn.batchDeclareSize) ) +  '条）';
        openwin(rurl('online/declare/amend_no.html?id='+getUrlParam('id') + "&statusId=" + $("#statusId").val() + "&orderStatus=" + $("#orderStatus").val() + "&waybillOrderNo=" + $("#s_docNo").val() + "&codeTs=" + $("#s_codeTs").val()  + "&batchDeclareSize=" + fn.batchDeclareSize + "&memberIds=" + ids.join(",") ),title,{area: ['700px', '500px'],shadeClose:true});
    });
    $("#updateHead").click(function () {
        var ids = [];
        var datas = layui.table.checkStatus("vehicle-detailed-list").data;
        $.each(datas,function (i,o) {
            ids.push(o.id);
        });
        if(ids.length != 1) {
           show_error("请选择一条清单记录修改表头");
           return;
        }
        //打开修改清单表体窗口
        openwin(rurl('online/declare/update_head.html?id='+ ids[0]),'修改清单表头',{area: ['860px', '420px'],shadeClose:true});
    });
    $("#updateBody").click(function () {
        var ids = [];
        var datas = layui.table.checkStatus("vehicle-goods-list").data;
        $.each(datas,function (i,o) {
            ids.push(o.id);
        });
        if(ids.length != 1) {
            show_error("请选择一条记录修改表体");
            return;
        }
        //打开修改清单表体窗口
        openwin(rurl('online/declare/update_body.html?id='+ ids[0]),'修改清单表体',{area: ['860px', '420px'],shadeClose:true});
    });
    $('#delete').click(function (){
        fn.delete();
    });
    $('#waybillCancel').click(function (){
        fn.waybillCancel();
    });
    $('#saveDec').click(function (){
        fn.saveDec();
    });
    $('#refresh').click(function (){
        $("#vehicle-declare-goods").hide();
        fn.init();
    });
    $('.query-btn').click(function (){
        $("#vehicle-declare-goods").hide();
        fn.clickQuery = '1';
        fn.vehicleDetailedList({
            'vehicleDeclareId':getUrlParam('id'),
            'docNo':$("#s_docNo").val(),
            'statusId':$("#statusId").val(),
            'orderStatus':$("#orderStatus").val(),
            'codeTs':$("#s_codeTs").val()
        });
    });
    $('.reset-btn').click(function (){
        fn.clickQuery = '1';
        $("#s_docNo").val('');
        $("#statusId").val('');
        $("#orderStatus").val('');
        $("#s_codeTs").val('');
        $("#vehicle-declare-goods").hide();
        fn.vehicleDetailedList({
            'vehicleDeclareId':getUrlParam('id')
        });
    });

    table.on('checkbox(vehicle-detailed-list)', function(obj){
        if(obj.checked){//判断当前多选框是选中还是取消选中
            fn.clickQuery = '0';
            $("#statusId").val('');
            $("#orderStatus").val('');
            $("#s_docNo").val('');
            $("#s_codeTs").val('');
        }
    });
    table.on('row(vehicle-detailed-list)', function(obj){
        var data = obj.data;
        $("#vehicle-declare-goods").show();
        let declareGoodsTitle = "清单表体" + "（" + "清单编号：" + data.detailedNo + "，运单编号：" + data.waybillNo + "，订单编号：" + data.orderNo  + "）";
        $("#declare-goods-title").html(declareGoodsTitle);
        fn.vehicleGoodsList({'vehicleDeclareOrderId':data.id})
    });
    //监听单元格事件
    table.on('tool(vehicle-detailed-list)', function(obj){
        console.log('单元格事件')
        var data = obj.data;
        if(obj.event == 'showInvtMemo'){
            if(isNotEmpty(data.statusMemo)) {
                layer.msg(data.statusMemo);
            }
        } else if (obj.event == 'showGood') {
            $("#vehicle-declare-goods").show();
            let declareGoodsTitle = "清单表体" + "（" + "清单编号：" + data.detailedNo + "，运单编号：" + data.waybillNo + "，订单编号：" + data.orderNo  + "）";
            $("#declare-goods-title").html(declareGoodsTitle);
            fn.vehicleGoodsList({'vehicleDeclareOrderId':data.id})
        } else if(obj.event == 'showInvtCancelGood'){
            if(isNotEmpty(data.inventoryCancelStatusMemo)) {
                layer.msg(data.inventoryCancelStatusMemo);
            }
        } else if (obj.event == 'editHead') {
            //打开修改清单表体窗口
            openwin(rurl('online/declare/update_head.html?id='+ data.id),'修改清单表头',{area: ['860px', '420px'],shadeClose:true});
        }
    });
});

function fullCustomerData(data) {
    $('#customerId').val(data.id);
}
